#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.db import *
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import InvalidURLError
import feedparser
import re

class RSS(db.Model):
  url=db.LinkProperty(required=True)
  title=db.StringProperty(required=False)
  subtitle=db.TextProperty(required=False)
  language=db.StringProperty(required=False)
  def updateArticles(self, user,forced=False,test=False):
    if test:
        return
    result = urlfetch.fetch(self.url)   
    entries = feedparser.parse(result.content).entries
    #entries = feedparser.parse("C:/Documents and Settings/Toi/workspace/contentsreaders/newsviewers/src/test/rss20.xml").entries
    for entry in entries:
      if 'link' not in entry.keys():
        # if no link then don't add this in articles
        continue
      # search an article with this link
      query = GqlQuery("SELECT * from RSS_ARTICLE where rss = :1 AND link = :2",self,entry.link)
      article = query.count()
      if article > 0 and not forced:
        # article already added
        pass
      else:
        # create a new article
        ra=RSS_ARTICLE(link=entry.link)
        ra.title=entry.title
        ra.rss=self.key()
        if "info_detail" in entry.keys():
            ra.base=entry.info_detail.base
        if "content" in entry.keys():
          ra.content="\n".join([text.value for text in entry.content])
          ra.updateMainImage()
        elif "summary_detail" in entry.keys():
          ra.content = entry.summary_detail['value']
          ra.updateMainImage()
        if 'updated_parsed' in entry.keys():
          (y,m,d,h,mn,sec,ms,tz,x)=entry.updated_parsed
          ra.date=datetime.datetime(y,m,d,h,mn,sec)
        elif 'published_parsed' in entry.keys():
          (y,m,d,h,mn,sec,ms,tz,x)=entry.published_parsed
          ra.date=datetime.datetime(y,m,d,h,mn,sec)
        elif 'created_parsed' in entry.keys():
          (y,m,d,h,mn,sec,ms,tz,x)=entry.created_parsed
          ra.date=datetime.datetime(y,m,d,h,mn,sec)

        ra.put()
        # link this article with the user
        ra_user = RSS_ARTICLE_USER(user=user,rss_article=ra,rss=self)
        ra_user.date = ra.date
        ra_user.put()
    db.put(self)

class RSS_USER(db.Model):
  # User of the RSS.
  user = UserProperty(required=True)
  # RSS
  rss=db.ReferenceProperty(RSS,required=True)

class RSS_ARTICLE(db.Model):
  link=db.LinkProperty(required=True)
  title=db.StringProperty(required=False)
  content=db.TextProperty(required=False)
  date=db.DateTimeProperty(required=False)
  rss=db.ReferenceProperty(RSS)
  mainImage=db.StringProperty(required=False)
  base=db.StringProperty(required=False)
  def updateMainImage(self):
      if self.content!=None:
          images=re.search("<img.+src=\"([^\"]+)\"", self.content)
      if images !=None:
          self.mainImage=images.group(1)
          if not self.mainImage.startswith('http') and self.base != None:
              self.mainImage=self.base+self.mainImage
          db.put(self)

class RSS_ARTICLE_USER(db.Model):
  # User of the Article.
  user = UserProperty(required=True)
  # RSS_ARTICLE
  rss_article = db.ReferenceProperty(RSS_ARTICLE,required=True)
  # Date of this article (for order quickly the date of RSS_ARTICLE is copied to this variable)
  date = db.DateTimeProperty(required=False)
  # RSS
  rss = db.ReferenceProperty(RSS,required=False)
  # True if this article has been read
  read = db.BooleanProperty(required=False,default=False)
  
class VIEW_DATA(db.Model):
      # User of the Article.
      user = UserProperty(required=True)
      # View type
      type = db.StringProperty(required=False)
      # Current rss viewed
      rssId = db.StringProperty(required=False)
